package com.example.service.impl;

import com.alibaba.fastjson2.JSON;
import com.example.constant.RedisConstants;
import com.example.domain.LoginUser;
import com.example.domain.User;
import com.example.service.LoginService;
import com.example.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;

    private final JwtUtil jwtUtil;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Map<String, String> login(User user) {
        // 用户认证
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token); // 密码编码器是在 authenticationManager.authenticate(token) 里面被调用
        // 认证失败
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 认证成功
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String generateToken = jwtUtil.generateToken(userId, null);
        stringRedisTemplate.opsForValue().set(RedisConstants.USER_TOKEN + userId, JSON.toJSONString(loginUser));
        return Map.of("token", generateToken);
    }

}
